import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { PermissionInfo } from '@/types/permission.type'
import { getCurrentUserPermissionTree } from '@/api/permission'
import { baseRoutes } from '@/router/baseRoutes'

// 权限树本地存储的key
const PERMISSION_TREE_KEY = 'permission_tree'

export const usePermissionStore = defineStore('permission', () => {
  // 权限树
  const permissionTree = ref<PermissionInfo[]>([])
  // 标记是否已获取权限树
  const hasFetchedPermissionTree = ref(false)
  
  // 菜单列表
  const menuList = computed(() => {
    console.log('生成菜单列表，权限树:', permissionTree.value)
    
    // 获取基础路由中的根路由
    const rootRoute = baseRoutes.find(route => route.path === '/')
    const baseMenus = rootRoute?.children || []
    
    // 过滤出需要显示的菜单项
    const filterMenus = (permissions: PermissionInfo[]): PermissionInfo[] => {
      return permissions.filter(permission => {
        if (permission.permissionType === 1) { // 菜单类型
          if (permission.children && permission.children.length > 0) {
            permission.children = filterMenus(permission.children)
          }
          return true
        }
        return false
      })
    }
    
    // 合并基础菜单和权限树中的菜单
    const menus = [...baseMenus, ...filterMenus(permissionTree.value)]
    console.log('生成的菜单列表:', menus)
    return menus
  })

  // 获取当前用户权限树
  const fetchPermissionTree = async () => {
    // 如果已经获取过权限树，直接返回
    if (hasFetchedPermissionTree.value) {
      console.log('权限树已获取，直接返回')
      return
    }

    try {
      // 尝试从本地存储获取权限树
      const cachedTree = localStorage.getItem(PERMISSION_TREE_KEY)
      if (cachedTree) {
        try {
          const parsedTree = JSON.parse(cachedTree)
          if (Array.isArray(parsedTree)) {
            permissionTree.value = parsedTree
            hasFetchedPermissionTree.value = true
            console.log('权限树设置成功:', permissionTree.value)
            return
          }
        } catch (e) {
          // 如果解析失败，清除缓存
          localStorage.removeItem(PERMISSION_TREE_KEY)
        }
      }

      // 从服务器获取权限树
      const data = await getCurrentUserPermissionTree()
      console.log('获取到的权限树数据:', data)
      
      if (Array.isArray(data)) {
        permissionTree.value = data
        hasFetchedPermissionTree.value = true
        // 缓存权限树
        localStorage.setItem(PERMISSION_TREE_KEY, JSON.stringify(data))
        console.log('权限树设置成功:', permissionTree.value)
      } else {
        console.warn('权限树数据无效:', data)
        permissionTree.value = []
      }
    } catch (error) {
      console.error('获取权限树失败:', error)
      permissionTree.value = []
    }
  }

  // 根据路径获取权限
  const getPermissionByPath = (path: string): PermissionInfo | undefined => {
    const findPermission = (permissions: PermissionInfo[]): PermissionInfo | undefined => {
      for (const permission of permissions) {
        if (permission.path === path) {
          return permission
        }
        if (permission.children) {
          const found = findPermission(permission.children)
          if (found) {
            return found
          }
        }
      }
      return undefined
    }
    return findPermission(permissionTree.value)
  }

  // 检查是否有权限
  const hasPermission = (path: string): boolean => {
    return !!getPermissionByPath(path)
  }

  // 重置权限
  const resetPermission = () => {
    permissionTree.value = []
    hasFetchedPermissionTree.value = false
    // 清除本地存储的权限树
    localStorage.removeItem(PERMISSION_TREE_KEY)
  }

  return {
    permissionTree,
    menuList,
    fetchPermissionTree,
    getPermissionByPath,
    hasPermission,
    resetPermission
  }
}) 